﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IService;
using DFGK_WMS.Model.Dto;
using DFGK_WMS.Model.Dto.YS;
using DFGK_WMS.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service
{
    public class InventoryLogService : BaseService, IInventoryLogService
    {
        private readonly IMaterialPackageRepository _materialPackageRepository;
        private readonly IInventoryLogRepository _inventoryLogRepository;
        public InventoryLogService(IMapper mapper, IInventoryLogRepository _inventoryLogRepository, IMaterialPackageRepository _materialPackageRepository) : base(mapper)
        {
            this._materialPackageRepository = _materialPackageRepository;
            this._inventoryLogRepository = _inventoryLogRepository;
        }

        public List<InventoryLogDto> GetInventoryflow(long WarehouseId, long AreaId, int SourceType, string? MaterialName, int pageIndex, int pageSize, out int totalCount)
        {
            var list = _inventoryLogRepository.GetEntityAlls();

            if (WarehouseId > 0)
            {
                list = list.Where(x => x.WarehouseId == WarehouseId);
            }
            if (AreaId > 0)
            {
                list = list.Where(x => x.AreaId == AreaId);
            }
            if (SourceType < 5)
            {
                list = list.Where(x => x.SourceType == SourceType);
            }
            if (!string.IsNullOrEmpty(MaterialName))
            {
                list = list.Where(x => x.MaterialName.Contains(MaterialName));
            }
            totalCount = list.Count();
            var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();
            List<InventoryLogDto> inventorylogdto = new List<InventoryLogDto>();
            foreach (var item in list)
            {
                InventoryLogDto inventorylogdtos = new InventoryLogDto();
                inventorylogdtos = mapper.Map<InventoryLogDto>(item);
                var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == item.MaterialId);
                if (materpackobj != null)
                {
                    if (item.AreaName == "整区")
                    {
                        inventorylogdtos.StartQty = inventorylogdtos.StartQty / materpackobj.ConversionFactor;
                        inventorylogdtos.ChangeQty = inventorylogdtos.ChangeQty / materpackobj.ConversionFactor;
                        inventorylogdtos.EndQty = inventorylogdtos.StartQty + inventorylogdtos.ChangeQty;
                    }
                    else
                        inventorylogdtos.BaseUnitName = materpackobj.SubPackageUnitName;
                }
                inventorylogdtos.CreateDates = item.CreateDate.HasValue ? item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "无日期";
                inventorylogdto.Add(inventorylogdtos);
            }
            return inventorylogdto.OrderByDescending(x => x.CreateDates).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }
        public List<ErpGetInventoryLogDto> ERPGetInventoryflow(string? Sourcesn, string? MaterialName, int pageIndex, int pageSize, out int totalCount)
        {
            // 获取所有库存日志
            var list = _inventoryLogRepository.GetEntityAlls();

            // 根据物料名称过滤
            if (!string.IsNullOrEmpty(MaterialName))
            {
                list = list.Where(x => x.MaterialName.Contains(MaterialName));
            }

            // 根据来源单号过滤
            if (!string.IsNullOrEmpty(Sourcesn))
            {
                list = list.Where(x => x.SourceSn.Contains(Sourcesn));
            }

            // 获取记录总数
            totalCount = list.Count();

            // 获取物料包信息
            var materpacklist = _materialPackageRepository.GetEntityAlls().ToList();

            // 创建 DTO 列表
            List<ErpGetInventoryLogDto> inventorylogdto = new List<ErpGetInventoryLogDto>();

            // 遍历过滤后的日志并合并变更数量
            var groupedLogs = list
                .GroupBy(x => x.SourceSn) // 按 SourceSn 分组
                .Select(g => new
                {
                    SourceSn = g.Key,
                    
                    TotalChangeQty = g.Sum(x => x.ChangeQty ?? 0), // 合并变更数量
                    FirstItem = g.First() // 获取分组中的第一个项以获取其他信息
                });

            foreach (var group in groupedLogs)
            {
                // 手动创建 DTO 对象并填充属性
                var inventorylogdtos = new ErpGetInventoryLogDto
                {
                    SourceType= group.FirstItem.SourceType,
                    SourceSn = group.SourceSn, // 从分组获取 SourceSn
                    ChangeQty = group.TotalChangeQty, // 使用合并的变更数量
                    CreateDates = group.FirstItem.CreateDate.HasValue ? group.FirstItem.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "无日期" // 格式化日期
                };

                // 查找物料包信息
                var materpackobj = materpacklist.FirstOrDefault(x => x.MaterialId == group.FirstItem.MaterialId);
                if (materpackobj != null && group.FirstItem.AreaName == "整区")
                {
                    // 根据转换因子调整变更数量
                    inventorylogdtos.ChangeQty = inventorylogdtos.ChangeQty / materpackobj.ConversionFactor;
                }

                // 添加到结果列表
                inventorylogdto.Add(inventorylogdtos);
            }

            // 返回分页结果，按生成日期降序排序
            return inventorylogdto
                .OrderByDescending(x => x.CreateDates) // 确保 CreateDates 是可用的
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToList();
        }
    }
}
